<template>
  <div id="EditAccount">
    <el-dialog :title="`${isCreate ? '添加' : '编辑'}台账`" :visible="visible" :before-close="handleClose" width="400px" @open="handleOpen">
      <el-form class="accountForm" ref="editForm" :model="editForm" :rules="rules" label-width="auto">
        <el-form-item label="所属月份：" prop="date">
          <el-date-picker disabled v-model="editForm.date" value-format="yyyy-MM" type="month" placeholder="选择年月份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属公司：" prop="subId">
          <el-select v-model="editForm.subId" :disabled="!isCreate" filterable clearable style="width:auto;" @change="handleCompanyChange">
            <el-option v-for="item in companyList" :key="item.subid" :value="item.subid" :label="item.subName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="台账名称：" prop="ledgerName">
          <el-input v-model="editForm.ledgerName" :validate-event="false"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleNextStep" v-if="isCreate">下一步</el-button>
        <el-button type="primary" @click="handleSubmit" v-else>保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getCompanyList } from "@/util/xc/utils";
import { mapState } from "vuex";
export default {
  name: 'EditAccount',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    isCreate: {
      type: Boolean,
      default: true,
    },
    editData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    yearNumber: {
      type: Number,
      default: () => {
        return new Date().getFullYear();
      }
    },
    monthNumber: {
      type: Number,
      default: () => {
        return new Date().getMonth() + 1;
      }
    }
  },
  data() {
    return {
      editForm: {
        subId: '',
        date: `${new Date().getFullYear()}-${new Date().getMonth() + 1}`,
        ledgerName: '',
        subName: '', // 当前选中的子公司名称
      },
      // rules: {
      //   subId: [
      //     { required: true, message: '请选择所属公司', trigger: 'blur' },
      //   ],
      //   ledgerName: [
      //     { required: true, message: '请输入台账名称', trigger: 'blur' },
      //     { validator: checkNameRepeat, trigger: 'blur' }
      //   ],
      // }
    };
  },
  computed: {
    ...mapState({
      companyList: state => state.reward.companyList,
    }),
    rules() {
      return {
        subId: [
          { required: true, message: '请选择所属公司', trigger: 'blur' },
        ],
        ledgerName: [
          { required: true, message: '请输入台账名称', trigger: 'blur' },
          { validator: this.checkNameRepeat }
        ],
      }
    }
  },
  methods: {
    checkNameRepeat(rule, value, callback) {
      const requestData = {
        ledgerId: this.isCreate ? 0 : this.editData.id,
        ledgerName: value,
        yearNumber: this.yearNumber,
        monthNumber: this.monthNumber,
        sqlType: this.isCreate ? 1 : 2,
        // companyId: this.editForm.subId
      }
      this.$api.socialSecurity
        .RegLedgerName(requestData)
        .then(res => {
          callback();
        })
        .catch(err => {
          callback(new Error(err.data.message));
        });
    },
    handleClose() {
      this.$refs.editForm.resetFields();
      this.$emit('update:visible', false);
    },
    handleOpen() {
      if (!this.isCreate) {
        console.log('this.editData', this.editData);
        this.editForm = {
          subId: this.editData.subId,
          date: `${this.editData.yearNumber}-${this.editData.monthNumber}`,
          ledgerName: this.editData.standingBookName,
        };
      }
    },
    handleSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {

          this.$emit(
            'editDeleteAccount',
            {
              ledgerId: this.editData.id,
              ledgerName: this.editForm.ledgerName
            }
            , 1);
          this.handleClose();
        } else {
          return false;
        }
      });
    },
    handleCompanyChange(data) {
      const result = this.companyList.find(e => e.subid == data);
      this.editForm.subName = result ? result.subName : '';
    },
    handleNextStep() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          const routeData = {
            subId: this.editForm.subId,
            yearNumber: this.editForm.date.substring(0, 4),
            monthNumber: this.editForm.date.substring(5, 9),
            ledgerName: this.editForm.ledgerName,
            subName: this.editForm.subName,
            ledgerId: 0,
          };
          // console.log('data', routeData);
          // 将数据存入vuex中
          this.$store.commit('SET_ACCOUNT_ROUTER_DATA', routeData);
          this.$router.push({
            path: '/socialSecurityAccountDetails',
            query: {
              fromPage: 'editAccount'
            },
          });

          this.handleClose();

        } else {
          return false;
        }
      });
    }
  },
  mounted() {
    getCompanyList();
  }
};
</script>
<style lang="less" scoped>
#EditAccount {
  .accountForm {
    width: 250px;
    margin-left: 50%;
    transform: translateX(-50%);

    :deep(.el-form-item) {
      .el-input,
      .el-select {
        width: 160px;
      }
    }
  }
}
</style>